<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品Id" prop="skuId">
        <el-input
          v-model="queryParams.skuId"
          placeholder="请输入商品Id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item  prop="warehouseId">
<!--        <el-input-->
<!--          v-model="queryParams.warehouseId"-->
<!--          placeholder="请输入仓库id"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
        <el-form-item label="请选择仓库" label-width="100px">
          <el-select v-model="queryParams.warehouseId" @click="handleQuery" clearable>
            <el-option v-for="item in warehouse" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId"></el-option>
          </el-select>
        </el-form-item>


      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xiaocui:procurement:add']"
        >添加采购需求</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['xiaocui:procurement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['xiaocui:procurement:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['xiaocui:procurement:export']"
        >导出</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <template>
      <el-button
                 @click="merge"
      >合并整单</el-button>
    </template>
<!--    {{this.proPur.proIds}}-->
<!--    <h1>选中id{{this.procurement}}</h1>-->

    <el-table v-loading="loading" :data="procurementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="采购Id" align="center" prop="procurementId" />
<!--      <el-table-column label="商品Id" align="center" prop="skuId" />-->
      <el-table-column label="商品名称" align="center" prop="skuName" />
      <el-table-column label="商品的数量" align="center" prop="productCount" />
      <el-table-column label="采购金额" align="center" prop="procurementPrice" />
<!--      <el-table-column label="仓库id" align="center" prop="warehouseId" />-->
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="状态" align="center" prop="status" :formatter="formatStatus"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xiaocui:procurement:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xiaocui:procurement:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


<!--    合并整单弹出框-->
    <el-dialog :title="title" :visible.sync="merges" width="500px" append-to-body>
<!--      先进行循环 然后把合并单id显示出来-->
      <el-form ref="form" :model="proPur" :rules="rules" label-width="100px">
        <el-form-item label="请选择采购单">
        <el-select v-model="proPur.purId" @click="handleSelectChange">
          <el-option v-for="item in proPur.proIds" :key="item" :label="item" :value="item"></el-option>
        </el-select>
        </el-form-item>
      </el-form>
      <div  class="dialog-footer">
        <el-button type="primary" @click="submitMergeForm">确 定</el-button>
        <el-button @click="cancelMerge">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改采购需求申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品Id" prop="skuId">
          <el-input v-model="form.skuId" placeholder="请输入商品Id" />
        </el-form-item>
        <el-form-item label="商品的数量" prop="productCount">
          <el-input v-model="form.productCount" placeholder="请输入商品的数量" />
        </el-form-item>
        <el-form-item label="请选择仓库">
          <el-select v-model="form.warehouseId" @click="handleSelectChange">
            <el-option v-for="item in warehouse" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProcurement,
  getProcurement,
  delProcurement,
  addProcurement,
  updateProcurement,
  MergeProcurement, getPurchase, addPurchase, warehouseShow
} from '@/api/xiaocui/procurement'
import axios from 'axios'
import item from '@/layout/components/Sidebar/Item.vue'
import { listWarehouse } from '@/api/xiaocui/warehouse'

export default {
  name: "Procurement",
  data() {
    return {
      num: 0,
      //仓库动态下拉
      warehouse:[],
      //像后台传的参数,用于创建或给需求申请表id
      addPurchaseReq:{
        ids:[],
        procurementId:null,
      },
      //建立个对象 然后进行判断 一个需求id 一个采购单id
      procurement:[],
      //向后台传入一个采购单的id 传多个或者一个采购需求单
      proPur:{
        purId:'',
        //采购单id
        proIds:[]
      },
      //合并
      merges:false,
      // 遮罩层
      loading: true,
      //选中采购id
      pIds:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购需求申请表格数据
      procurementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        skuId: null,
        warehouseId: null,
      },
      // 表单参数
      form: {
        //仓库id
        warehouseId:[],
      },
      // 表单校验
      rules: {
      }
    };
  },
  //创建
  created() {
    this.getWarehouseList();
    this.getPurchase();
    this.getList();
  },
  computed:{
    formatStatus(){
      return(row,column,cellValue)=>{
        //根据status返回不同的值
        switch (cellValue) {
          case 1:
            return <el-tag style="background-color: #ffebcd;">新建</el-tag>;
          case 2:
            return <el-tag style="background-color: #add8e6;">采购中</el-tag>;
          case 3:
            return <el-tag style="background-color: #98fb98;">采购完成</el-tag>;
        }
      }
    }



  },
  methods: {

    //仓库的动态下拉数组
    /** 查询仓库列表 */
    getWarehouseList() {
      warehouseShow().then(res => {
        this.warehouse=res.data;
      });
    },
    beforeDestroy(){
      clearInterval(this.timer);
    },
    //点击
    handleSelectChange(){
      this.proPur.proIds = [];
    },
    //合并确定和取消
    submitMergeForm(){

      let flag =true;
      if(this.procurement.length==0){
        alert("请选择要合并的id");
        return;
      }
      // //把选中的数据 循环遍历出来 然后进行判断
      this.procurement.forEach((res=>{
        //判断选中当中的申请单id有没有值  有的话就列出来
        if(res.procurementId!=null){
          this.addPurchaseReq.ids.push(res.id);
          flag =false;
        }
      }))
      //如果有采购单id的值 就提醒哪个id已经选择 就不能选择了
      if(flag==false){
        alert("您选择的id为:"+this.addPurchaseReq.ids+"已经有采购单,请重新选择");
        this.addPurchaseReq.ids=[];
        return;
      }
      this.procurement.forEach((res=>{
        //判断选中当中的申请单id有没有值  有的话就列出来
          this.addPurchaseReq.ids.push(res.id)
      }))
      //再判断有没有选择的合并单id
      if(this.proPur.purId==0){
        alert("您是否要创建一个新的采购单进行合并?");
        //给后台传Ids this.Ids
       addPurchase(this.addPurchaseReq).then(res=>{
         if(res.code==200){
           alert("创建成功");
           this.merges=false;
           this.getPurchase();
           this.getList();
           this.addPurchaseReq.ids=[];
         }
       });
       return;
      }
      // alert(this.addPurchaseReq.ids) //选中的id
      this.addPurchaseReq.procurementId = this.proPur.purId;
      addPurchase(this.addPurchaseReq).then(res=>{
        console.log(res);
        if(res.code==200){
          alert("合并成功")
          this.proPur.purId = '';
          this.merges = false;
          this.getPurchase();
          this.getList();
          this.addPurchaseReq.ids=[];
        }
      });
      this.addPurchaseRe.qids=[];
    },
    //取消
    cancelMerge(){
      this.merges = false;
    },
    //点击请求合并
    merge(){
      //点击刷新一下 采购单id
      this.getPurchase();
      this.merges=true;
    },
    //查询采购单中的id
    getPurchase(){
      this.proPur.proIds=[];
      getPurchase().then(
        res=>{
          console.log(res.data)
          //遍历res.data数组 并将每一个元素proId添加到proIds当中
          res.data.forEach(item=>{
            if(item.procurementId){
              this.proPur.proIds.push(item.procurementId);
            }
          })
        }
      )
    },

    change(row){
      const ids = row.id || this.ids;
      this.$prompt('请选择', '合并到整单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputErrorMessage: '邮箱格式不正确'
      }).then(({ value }) => {
        this.$message({
          type: 'success',
          message: '合并成功'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消'
        });
      });
    },
    /** 查询采购需求申请列表 */
    getList() {
      this.loading = true;
      listProcurement(this.queryParams).then(response => {
        this.procurementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        procurementId: null,
        skuId: null,
        productCount: null,
        procurementPrice: null,
        warehouseId: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.procurement = selection.map(item => item)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getWarehouseList();
      this.reset();
      this.open = true;
      this.title = "添加采购需求申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProcurement(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购需求申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null ) {
            updateProcurement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProcurement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购需求申请编号为"' + ids + '"的数据项？').then(function() {
        return delProcurement(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xiaocui/procurement/export', {
        ...this.queryParams
      }, `procurement_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
